package com.kaiyidiannao.activity.secondhandcar;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.kaiyidiannao.adapter.CommonViewpagerAdapter;
import com.kaiyidiannao.common.BaseActionBarActivity;
import com.kaiyidiannao.data.DataCenter;
import com.kaiyidiannao.main.R;
import com.kaiyidiannao.model.bean.SecondHandCar;
import com.kaiyidiannao.model.req.model.GetSecondHandCarShow;
import com.kaiyidiannao.model.req.model.PostAddFavorites;
import com.kaiyidiannao.view.ActionBarView;
import com.taplinker.core.util.LogUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

/**
 * Created by mark on 2014/4/14.
 */
public class SecondHandCarDetail extends BaseActionBarActivity implements View.OnClickListener, Observer {

    private ImageView storeCall;
    private SecondHandCar bean;
    private TextView secondHandCarName, carPrice, outLook, sellerPhoneNum, sellerDetails,publishTime;
    private ImageView collect;
    private String userid;
    private String itemid;
    private String addtime;
    private boolean collectFlag;
    private ArrayList<SecondHandCar> secondHandCars = DataCenter.secondHandCarShow;
//    private ViewPager detailViewPager;
//    private CommonViewpagerAdapter commonViewpagerAdapter;
//    private List<View> imageList = new ArrayList<View>();
//    private List<String> imageUrlList = new ArrayList<String>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.secondhandcar_detail);
        DataCenter.getInstance().addObserver(this);
        initID();
        Intent intent = getIntent();

        itemid = intent.getStringExtra("itemid");
        //catid = intent.getStringExtra("catid"); //catid是固定的64
        addtime = intent.getStringExtra("addtime");


        showProgressDialog();
        if(isLogin()){
            userid = getUserid();
            new GetSecondHandCarShow(Integer.parseInt(itemid),userid, DataCenter.CATID_SECOND_CAR +"").execute();
        }else {
            new GetSecondHandCarShow(Integer.parseInt(itemid)).execute();
        }

        findActionBar();
    }

    public void setView() {
        secondHandCarName.setText(bean.getTitle());
        carPrice.setText(bean.getPrice()+"万");
        outLook.setText(bean.getCondition()+"成新");
        sellerPhoneNum.setText(bean.getTelephone());
        sellerDetails.setText(bean.getIntroduce());
        collect.setOnClickListener(this);
        storeCall.setOnClickListener(this);

        if (bean.isIs_fav()) { // 已经收藏
            collect.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.shoucanged));
            collectFlag = true;
        } else {
            collect.setImageBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.shoucang));
            collectFlag = false;
        }
        publishTime.setText(bean.getAddtime());
        //八张详情图片
        imageUrlList = bean.getPicture2();
        initViewPage();
    }

    private void initID() {
        storeCall = (ImageView) findViewById(R.id.storeCall);
        sellerPhoneNum = (TextView) findViewById(R.id.sellerPhoneNum);
        secondHandCarName = (TextView) findViewById(R.id.secondHandCarName);
        carPrice = (TextView) findViewById(R.id.carPrice);
        outLook = (TextView) findViewById(R.id.outLook);
        sellerDetails = (TextView) findViewById(R.id.sellerDetails);
        collect = (ImageView) findViewById(R.id.collect);
        publishTime = (TextView)findViewById(R.id.publishTime);
        //八张详情图片
        detailViewPager = (ViewPager) findViewById(R.id.detail_ViewPager);
    }

    /**
     * 初始化8张详情图片
     */
    private ViewPager detailViewPager;
    private CommonViewpagerAdapter commonViewpagerAdapter;
    private List<View> imageList = new ArrayList<View>();
    private List<String> imageUrlList = new ArrayList<String>();

    private void initViewPage() {

        commonViewpagerAdapter = new CommonViewpagerAdapter(SecondHandCarDetail.this, imageList, detailViewPager, imageUrlList);

        for (int i = 0; i < imageUrlList.size(); i++) {
            final int position = i;
            ImageView imageView = (ImageView) getLayoutInflater().inflate(R.layout.common_viewpager_item, null);
            imageLoader.displayImage(imageUrlList.get(i), imageView, super.options, null);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    SecondHandCarDetail.super.startImagePagerActivity(position, bean.getPicture());
                }
            });
            imageList.add(imageView);
        }

        detailViewPager.setAdapter(commonViewpagerAdapter);
    }

    /**
     * 显示重新加载页面
     */
    private void showReloadView() {
        findViewById(R.id.secondcar_detail_scrollview).setVisibility(View.GONE);
        findViewById(R.id.realod_layout).setVisibility(View.VISIBLE);
        findViewById(R.id.reload).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showProgressDialog();
                findViewById(R.id.secondcar_detail_scrollview).setVisibility(View.INVISIBLE);
                findViewById(R.id.realod_layout).setVisibility(View.GONE);
                if(isLogin()){
                    userid = getUserid();
                    new GetSecondHandCarShow(Integer.parseInt(itemid),userid, DataCenter.CATID_SECOND_CAR +"").execute();
                }else {
                    new GetSecondHandCarShow(Integer.parseInt(itemid)).execute();
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        if (null != bean) {
            if (isLogin()) {
                switch (v.getId()) {
                    case R.id.storeCall:
                        String phoneNum = (String) sellerPhoneNum.getText();
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_CALL);
                        intent.setData(Uri.parse("tel:" + phoneNum));
                        startActivity(intent);
                        break;
                    case R.id.collect:
                        String action = "add";
                        if (collectFlag) {
                            action = "delete";
                        }
                        showProgressDialog();
                        // 收藏，点赞的catid是固定的，二手车（64）
                        new PostAddFavorites(DataCenter.CATID_SECOND_CAR, userid, action, bean.getItemid(), bean.getTitle()).execute();
                        break;
                }
            } else {
                startLoginOrRegistered();
            }
        } else {
            showToast("详情价值失败");
        }
    }

    private void findActionBar() {
        actionBarView = (ActionBarView) findViewById(R.id.actionbar);
    // actionBarView.setTitle("二手车详情");
       actionBarView.setTitle("二手车详情");        //actionBarView.button_right_icon1.setVisibility(View.VISIBLE);
        //actionBarView.button_right_icon1.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.publish));
    }

    @Override
    public void update(Observable observable, Object data) {
        DataCenter.flag flag = (DataCenter.flag) data;

        closeProgressDialog();

        if (flag == DataCenter.flag.GET_SECONDCAR_SHOW_SUCCESS) {
            if (null==DataCenter.secondHandCar ||  DataCenter.secondHandCarShow.size() == 0) {
                return;
            } else {
                findViewById(R.id.secondcar_detail_scrollview).setVisibility(View.VISIBLE);
                findViewById(R.id.realod_layout).setVisibility(View.GONE);
                bean = DataCenter.secondHandCarShow.get(0);
                if(bean != null){
                    if(bean.getPicture().length == 0){
                        detailViewPager.setBackgroundResource(R.drawable.ic_default);
                    }
                }
                setView();

            }
        } else if (flag == DataCenter.flag.GET_SECONDCAR_SHOW_FAILED) {
//            showToast("详情请求失败");
            showReloadView();
        }

        if (flag == DataCenter.flag.GetAddMESSAGEINFO_SUCCESS) {//收藏成功,关注成功\
            if (DataCenter.successFlag.equals(DataCenter.successFlag)) {
                if (collectFlag) {//从当前的关注状态变成没有关注
                    collectFlag = false;
                    //取消收藏
                    showToast(R.string.collect_cancle);
                    collect.setImageBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.shoucang));
                } else {
                    //收藏成功
                    showToast(R.string.collect_add);
                    collectFlag = true;
                    collect.setImageBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.shoucanged));
                }
            } else {
                showToast(DataCenter.msg, "收藏出现错误");
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        LogUtil.d(DataCenter.LOG_INFO, SecondHandCarDetail.class.getSimpleName() + ".onDestroy");
        DataCenter.playBeanList.clear();
        //删除观察者
        DataCenter.getInstance().deleteObserver(this);

    }
}
